package org.lab.mtga.core.services;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.lab.mtga.core.model.ManaSource;

public class CMCParser {

	public Map<ManaSource, Integer> withCmc(String cmc) {
		Map<ManaSource, Integer> map = new LinkedHashMap<ManaSource, Integer>();
		Pattern pattern = Pattern.compile("(\\d+)");
		Matcher matcher = pattern.matcher(cmc);
		if (matcher.find()) {
			Integer value = Integer.parseInt(matcher.group(1));
			if (value > 0) {
				map.put(ManaSource.I, value);
			}
			cmc = matcher.replaceAll("");
		}
		Map<Pattern, ManaSource> patternMap = new LinkedHashMap<Pattern, ManaSource>();
		patternMap.put(Pattern.compile("\\(B/G\\)"), ManaSource.BG);
		patternMap.put(Pattern.compile("\\(B/R\\)"), ManaSource.BR);
		patternMap.put(Pattern.compile("\\(øB\\)"), ManaSource.øB);
		patternMap.put(Pattern.compile("B"), ManaSource.B);
		patternMap.put(Pattern.compile("G"), ManaSource.G);
		patternMap.put(Pattern.compile("R"), ManaSource.R);
		patternMap.put(Pattern.compile("W"), ManaSource.W);
		Boolean matches;
		for (Pattern i : patternMap.keySet()) {
			do {
				matcher = i.matcher(cmc);
				if (matcher.find()) {
					matches = true;
					ManaSource manaType = patternMap.get(i);
					if (map.containsKey(manaType)) {
						map.put(manaType, map.get(manaType) + 1);
					} else {
						map.put(manaType, 1);
					}
					cmc = matcher.replaceFirst("");
				} else {
					matches = false;
				}
			} while (matches);
		}
		if (cmc.length() != 0) {
			throw new RuntimeException("Invalid CMC expression: " + cmc);
		}
		return map;
	}
}
